const { Validator, Rule } = require('../../../../../core/validator/index')
const User = require('../../../../models/user')

class RegisterValidate extends Validator {
  constructor() {
    super()
    // 设置参数 & new 了一些规则
    // 必须是数组
    this.account = [
      // new Rule('isLength', '账号至少6个字符，最多22个字符', {
      //   min: 6,
      //   max: 22,
      // }),
      // new Rule('matches', '账号长度必须在6~22位之间，包含字符、数字和 _ ', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]'),
    ]
    this.email = [new Rule('isEmail', '电子邮箱不符合规范，请输入正确的邮箱')]
    this.password1 = [
      new Rule('isLength', '密码至少6个字符，最多22个字符', {
        min: 6,
        max: 22,
      }),
      new Rule('matches', '密码长度必须在6~22位之间，包含字符、数字和 _ ', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]'),
    ]
    this.password2 = this.password1
    this.nickname = [
      new Rule('isLength', '昵称长度必须在4~32之间', {
        min: 4,
        max: 32,
      }),
    ]
  }
  // 自定义检查方法
  validatePassword(requestParams) {
    const pwd1 = requestParams.body.password1
    const pwd2 = requestParams.body.password2
    if (pwd1 !== pwd2) {
      throw new Error('两次密码输入不一致')
    }
  }

  // 验证当前用户是否存在
  async validateEmail(requestParams) {
    const { email } = requestParams.body
    const user = await User.findOne({
      where: {
        email,
      },
    })
    if (user) {
      throw new Error('邮箱已被注册，请重新输入邮箱')
    }
  }
}
const verify = async (ctx, next) => {
  await new RegisterValidate().start(ctx)
  await next()
}

module.exports = {
  verify,
}
